package com.example.qing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.qing.config.LogType;
import com.example.qing.config.MyLogs;
import com.example.qing.pojo.Emp;
import com.example.qing.pojo.Result;
import com.example.qing.pojo.User;
import com.example.qing.service.EmpService;
import com.example.qing.service.UserService;
import com.example.qing.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @MyLogs(operation = "用户",type = LogType.LOGIN)
    public Result login(@RequestBody User user){
        QueryWrapper<User> queryWrapper=new QueryWrapper<User>()
                .eq("username",user.getUsername())
                .eq("password",user.getPassword());
        User e=userService.getOne(queryWrapper);
        if (e!=null){
            Map<String,Object>claims=new HashMap<>();
            claims.put("id",e.getId());
            claims.put("name",e.getName());
            claims.put("username",e.getUsername());

            String jwt=JwtUtils.generateJwt(claims);
            e.setToken(jwt);
            return Result.success(e);
        }
        return Result.error("用户名或密码错误");

    }
    @MyLogs(operation = "用户",type = LogType.REGISTER)
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        log.info("注册");
        userService.save(user);
        return Result.success();
    }
}
